package org.kalai.unifypay.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.kalai.unifypay.Constant;
import org.kalai.unifypay.SessionManager;
import org.kalai.unifypay.bean.Bizcnf;
import org.kalai.unifypay.bean.Member;
import org.kalai.unifypay.bean.Transflow;
import org.kalai.unifypay.util.CipherUtils;
import org.kalai.unifypay.util.CommonUtil;
import org.kalai.unifypay.util.DataDao;
import org.kalai.unifypay.util.ProxyPayUtil;

import com.alibaba.fastjson.JSON;

@WebServlet(urlPatterns="/AlipayNotify_backups")
public class Copy_2_of_MinsNotify extends HttpServlet {
	private static final long serialVersionUID = 4553766925571289786L;
	private static final Logger logger = Logger.getLogger(Copy_2_of_MinsNotify.class);
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		CommonUtil.responseObject(resp, Constant.ERROR_REQEST);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String encryptData = request.getParameter("encryptData");
		String encryptKey = request.getParameter("encryptKey");
		String signData = request.getParameter("signData");
		String tranxSN = request.getParameter("reqMsgId");
		String aesKey = CipherUtils.decryptRSA(CipherUtils.decryptBase64(encryptKey));
		String xmlMessage = CipherUtils.decryptAES(CipherUtils.decryptBase64(encryptData), aesKey);
		try {
			boolean flag = CipherUtils.designRSA(CipherUtils.decryptBase64(signData), xmlMessage);
			if(!flag) throw new RuntimeException("验证签名失败！");
			Transflow transflow = DataDao.getInstance().getTransflow(tranxSN);
			if(transflow == null) throw new RuntimeException(String.format("交易信息不存在[%s][%s]", tranxSN, xmlMessage));
			if(transflow.getStatus() == 1){//未处理的订单才进行处理
				Member member = DataDao.getInstance().getMember(transflow.getMemberNo());
				if (member == null) throw new RuntimeException("商户信息不存在:"+transflow.getMemberNo());
				
				String respCode = xmlMessage.substring(xmlMessage.indexOf("<respCode>") + 10, xmlMessage.indexOf("</respCode>"));
				String respDesc = xmlMessage.substring(xmlMessage.indexOf("<respMsg>") + 9, xmlMessage.indexOf("</respMsg>"));
				respCode = "000000".equals(respCode) ? "00" : respCode;
				String payAccount = xmlMessage.substring(xmlMessage.indexOf("<buyerAccount>") + 14, xmlMessage.indexOf("</buyerAccount>"));
				String buyerPayAmount = xmlMessage.substring(xmlMessage.indexOf("<buyerPayAmount>") + 16, xmlMessage.indexOf("</buyerPayAmount>"));
				boolean isok = "00".equals(respCode);
				logger.info(String.format("接收到民生异步通知[%s-%s-%s-%s]", tranxSN, buyerPayAmount, respCode, respDesc));
				//更新交易表
				DataDao.getInstance().updateTransflow(tranxSN, payAccount, Double.valueOf(Double.valueOf(buyerPayAmount)*100).longValue(), isok ? 2 : 3, respCode, isok ? "交易成功" :respDesc);
				String bizcode = transflow.getBizcode();
				Bizcnf bizcnf = DataDao.getInstance().getBizcnfByCode(bizcode);
				if(isok && bizcnf.getPattern() == 0){//D0交易成功后实时代付出去
					String settNo = CommonUtil.generSettNo();
					boolean rs = DataDao.getInstance().addSettlement(tranxSN, settNo, bizcode, member, transflow.getTransAmt() - transflow.getTransFee(), 1);
					if (rs) ProxyPayUtil.proxyPay(settNo, member, ((Double)(transflow.getTransAmt() * 100 - transflow.getTransFee() * 100)).longValue(), bizcode, true);
				}
				//异步通知账单系统
				CommonUtil.notifyTransFlow(transflow);
				//异步通知用户
				//异步通知用户
				String url = transflow.getNotifyUrl();
				String partnerCode = transflow.getPartnerCode();
				String secret = DataDao.getInstance().getPartnerByCode(partnerCode).getPartnerSecret();
				if(url != null && !"".equals(url)) 
					CommonUtil.notifyMessage(url, partnerCode, secret, tranxSN, transflow.getOrderNo(), transflow.getTransAmt(), 
							respCode, respDesc);
				//websocket推送消息
				Map<String, Object> result = CommonUtil.createRespMap(respCode, respDesc);
				SessionManager.getInstance().broadcast(tranxSN, JSON.toJSONString(result));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			CommonUtil.responseObject(response, "000000");
		}
	}
}
